package com.nowcoder.community.controller;

import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController {
    @Autowired
    DiscussPostService discussPostService;

    @Autowired
    UserService userService;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    MessageService messageService;

    @Autowired
    LikeService likeService;

    @GetMapping(path = {"index", "/"})
    public ModelAndView indexPage(Page page) {
        page.setRows(discussPostService.countDiscussPosts());
        page.setPath("/index");
        List<DiscussPost> list = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit());
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (list != null) {
            for (DiscussPost discussPost : list) {
                Map<String, Object> map = new HashMap<>();
                discussPost.setLikeCount(likeService.countPostLike(discussPost.getId()));
                map.put("post", discussPost);
                User user = userService.findUserById(discussPost.getUserId());
                map.put("user", user);
                discussPosts.add(map);
            }
        }

        ModelAndView ret = new ModelAndView("index")
                .addObject("discussPosts", discussPosts)
                .addObject("page", page);
        if (hostHolder.getUser() != null) {
            ret.addObject("totalUnread", messageService.countUserUnread(hostHolder.getUser().getId()));
        }

        return ret;
    }

    @GetMapping("/error")
    public String error() {
        return "/error/500";
    }


}
